package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WmMaterial uploadPicture(MultipartFile file) {
        if (WmThreadLocalUtil.getUser() == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //0.准备文件
        String originalFilename = file.getOriginalFilename(); //获取原始文件名 a.jpg
        int i = originalFilename.lastIndexOf(".");
        String fileName = UUID.randomUUID().toString();
        if (i > -1) {
            String suffix = originalFilename.substring(i);
            fileName = fileName + suffix; //拼接后缀
        }
        //1.上传文件
        String path = null;

        try {
            path = fileStorageService.uploadImgFile("", fileName, file.getInputStream());

            //2.保存到数据库
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(path);
            wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
            wmMaterial.setCreatedTime(new Date());
            save(wmMaterial);
            return wmMaterial;
        } catch (Exception e) {
            log.error("上传文件和保存数据库失败", e);
            if (StringUtils.isNotEmpty(path)) {
                fileStorageService.delete(path);
            }
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public PageResponseResult findPage(WmMaterialDto dto) {
        if (WmThreadLocalUtil.getUser() == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        dto.checkParam();

        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId())
                .orderByDesc(WmMaterial::getCreatedTime);
        if (Objects.equals(dto.getIsCollection(), WmMaterialDto.COLLECTION)) {
            //拼接上条件 筛选出收藏的图片
            wrapper.eq(WmMaterial::getIsCollection, WmMaterialDto.COLLECTION);
        }
        Page<WmMaterial> page = page(new Page<>(dto.getPage(), dto.getSize()), wrapper);
        PageResponseResult result = new PageResponseResult((int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }
}
